
let initDb = {
    resumeTitleList:[],
    jobTags:[],
    requireDescription:[],
    resumeContent:[]
}

import { createResumeList } from "./tables/resumeList"
import { createJobTag } from "./tables/jobTag.js"
import { createRequireDescription } from "./tables/requireDescription.js"



export class ConnectDb {
    static #onLineResumeDb
    static #IDBRequest;
    // 在类生成时运行，且只运行一次
    static {
        let request = window.indexedDB.open('onLineResume')
        ConnectDb.#IDBRequest = request


        request.onupgradeneeded = function(event){
            console.log('库表更新中')
            let db1 = event.target.result  //获取数据库实例

            // 创建表
            createResumeList(db1)
            createJobTag(db1)
            createRequireDescription(db1)
        }
    }


    async getDb(){
        if(ConnectDb.#onLineResumeDb){
            return ConnectDb.#onLineResumeDb
        }else{
            let promise = new Promise((resolve,reject)=>{
                if(ConnectDb.#IDBRequest.readyState === 'done'){
                    if(!ConnectDb.#IDBRequest.error){
                        resolve(ConnectDb.#IDBRequest.result)
                    }else{
                        reject(ConnectDb.#IDBRequest.error)
                    }
                }

                /**
                 * 以下内容只有初次打开时候会执行，如果刷新页面，该函数不会执行
                 */
                ConnectDb.#IDBRequest.onsuccess = function(event){
                    console.log('数据库打开成功')
                    let db = ConnectDb.#IDBRequest.result  //获取数据库对象
                    ConnectDb.#onLineResumeDb = db
                    resolve(db)
                }

                ConnectDb.#IDBRequest.onerror = function(event){
                    console.log('数据库打开报错')
                    reject('数据库打开报错')
                }

            })
            return promise
        }
    }


    async getObjectStore(store_name, mode = 'readonly') {
        let promise = new Promise(async(resolve,reject)=>{
            let store;
            let db = await this.getDb()
            let transaction
            transaction = db.transaction([store_name], mode);
            console.log('事务建立')
            store = transaction.objectStore(store_name);
            resolve(store)
        })
        return promise
    }
}



